#include "drawwidget.h"
#include <QPainter>
#include <QString>
#include "calfunc.h"

DrawWidget::DrawWidget(QWidget *parent) :
    QWidget(parent)
{

    line_num=0;
    s_step = 4;   //5 pixel
    line_color=NULL;
    line_data=NULL;

    QColor tmp[1];
    tmp[0]=Qt::blue;
    this->setLineNum(1,tmp);
}
//设定图形中的线条属性
//@param num 线条数目
//@param color 各条线条颜色的数组
void DrawWidget::setLineNum(int num, QColor *color)
{
    int i;
    line_num=num;
    line_color=new QColor[num];
    for(i=0;i<num;i++)
    {
        line_color[i]=color[i];
    }
//    坐标点数组
    line_data=new double[num*DATA_NUM];
    for(i=0;i<DATA_NUM*num;i++)
        line_data[i]=100;
}

DrawWidget::~DrawWidget()
{
//    回收资源
//    new出的对象必需delete
    delete[] line_color;
    delete[] line_data;
}

void DrawWidget::paintEvent(QPaintEvent *)
{
    QPainter *painter=new QPainter(this);
    painter->setPen(Qt::red);
    painter->drawRect(0,0,this->width()-1,this->height()-1);
    int i,j;
    painter->setPen(Qt::DotLine);
    for(i=1;i<10;i++)
    {
        painter->drawLine(0,height()*i/10,width(),height()*i/10);
        painter->drawLine(width()*i/10,0,width()*i/10,height());
    }
    int step=s_step;
    if(width()/(DATA_NUM-1) + 1 > s_step)
    {
        step = width()/(DATA_NUM-1) + 1;
    }
    for(i=0;i<line_num;i++)
    {
        painter->setPen(line_color[i]);
        for(j=0;j<DATA_NUM-1 && j*step < width();j++)
        {
            painter->drawLine(width()-step*j,line_data[DATA_NUM*i+DATA_NUM-1-j]*height()/100,
                              width()-step*(j+1),line_data[DATA_NUM*i+DATA_NUM-2-j]*height()/100);
        }
    }

    delete painter;
}
void DrawWidget::timerEvent(QTimerEvent *)
{
    double x[2];
    t_cpuinfo *cpuinfo=NULL;
    cpuinfo=::get_cpu(1);
     x[0]=100-cpuinfo->idle;
     x[1]=100-cpuinfo->user;
    this->pushData(x);
}

void DrawWidget::pushData(double *data)
{
    int i,j;
    for(i=0;i<line_num;i++)
    {
        for(j=0;j<DATA_NUM-1;j++)
        {
            line_data[i*DATA_NUM+j]=line_data[i*DATA_NUM+j+1];
        }
        line_data[i*DATA_NUM+j]=100-data[i];
    }
    this->update();
}
